//
//  ArticelTitleTableViewCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/22.
//

import UIKit
protocol ArticelTitlTableCellDelegate:NSObjectProtocol {
    func didSelectFavoryTableCell(atIndex: IndexPath);
}
class ArticelTitleTableViewCell: UITableViewCell {
    var delegate: ArticelTitlTableCellDelegate!
    var collectionView: UICollectionView!
    var dataArr = NSMutableArray()
    var pageControl: TYPageControl!
    var titleLab: UILabel!
    var subTitleLab: UILabel!
    var priceLab: UILabel!
    var bkgView: UIView!
    var indexPath: IndexPath!
    var data: CarDetailsContentModel!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = UIColor.init(hex: 0xF2F7FA)
        self.selectionStyle = .none
        bkgView = UIView.init(frame: CGRect.zero)
        bkgView.backgroundColor = UIColor.white
        bkgView.layer.cornerRadius = 4
        bkgView.layer.masksToBounds = true
        self.contentView.addSubview(bkgView)
                
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.bkgView.width, height: self.frame.size.height), collectionViewLayout: layout)
        collectionView.register(CarBannerCollectionCell.self, forCellWithReuseIdentifier: "CarBannerCollectionCell")
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        collectionView.isMultipleTouchEnabled = false
        
//        collectionView.layer.borderWidth = 1
//        collectionView.layer.borderColor = UIColor.blue.cgColor
        self.bkgView.addSubview(collectionView)
        
                
        self.pageControl = TYPageControl()
        self.pageControl.currentPageIndicatorSize = CGSize(width: 19, height: 2)
        self.pageControl.pageIndicatorSize = CGSize(width: 19, height: 2)
        self.pageControl.backgroundColor = .clear
        self.pageControl.currentPage = 0
//        self.pageControl.pageIndicatorImage = UIImage.init(named: "icon_banner_dot")
//        self.pageControl.currentPageIndicatorImage = UIImage.init(named: "icon_banner_dot_white")
        self.bkgView.addSubview(self.pageControl)
        
        
        titleLab = UILabel.init(frame: CGRect.init())
        titleLab.backgroundColor = UIColor.white
        titleLab.textAlignment = .left
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleLab.textColor = UIColor.black
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        bkgView.addSubview(titleLab)
        
        subTitleLab = UILabel.init(frame: CGRect.init())
        subTitleLab.backgroundColor = UIColor.white
        subTitleLab.textAlignment = .left
        subTitleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        subTitleLab.textColor = UIColor.init(hex: 0x939AA8)
        subTitleLab.lineBreakMode = .byTruncatingTail
        subTitleLab.numberOfLines = 1
        bkgView.addSubview(subTitleLab)
        
        priceLab = UILabel.init(frame: CGRect.init())
        priceLab.backgroundColor = UIColor.white
        priceLab.textAlignment = .right
        priceLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        priceLab.textColor = Theme.mainColor
        bkgView.addSubview(priceLab)
        
        self.addSnpLayout()
    }
    
    func addSnpLayout(){
        bkgView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(10)
            make.right.equalTo(-18)
            make.bottom.equalTo(0).priority(999)
        }
        
        let tempH: CGFloat = (kScreenWidth - 36) * 9/16
        self.collectionView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(tempH)
        }
        
        
        self.pageControl.snp.makeConstraints { make in
            make.centerX.equalTo(self.bkgView.snp.centerX)
            make.height.equalTo(2)
            make.width.equalTo(300)
            make.bottom.equalTo(self.collectionView.snp.bottom).offset(-14)
        }

        
        titleLab.snp.makeConstraints { make in
            make.top.equalTo(self.collectionView.snp.bottom).offset(12)
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(20)
        }
        
        subTitleLab.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.top.equalTo(titleLab.snp.bottom).offset(8)
            make.height.equalTo(16)
            make.bottom.equalTo(self.bkgView.snp.bottom).offset(-10)
        }
        
        priceLab.snp.makeConstraints { make in
            make.left.equalTo(subTitleLab.snp.right).offset(10)
            make.right.equalTo(-10)
            make.centerY.equalTo(subTitleLab.snp.centerY)
            make.height.equalTo(20)
//            make.bottom.equalTo(bkgView.snp.bottom).offset(-10)
        }
        subTitleLab.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)  //抗压缩
        priceLab.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) //抗压缩
        self.updateConstraints()
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///赋值
    func setFavoryCell(data: CarDetailsContentModel) {
        self.data = data
        self.dataArr.removeAllObjects()
        let bkgImg = self.data.backgroundImage ?? ""
        //外观
        var appearArray = (data.appearanceImages ?? "").components(separatedBy: ",")
        if bkgImg != "" {
            appearArray.insert(bkgImg, at: 0)
        }
        
        if appearArray.count > 4 {
            for index in 0 ..< 4 {
                let url = appearArray[index]
                self.dataArr.add(url)
            }
        }else{
            for index in 0 ..< appearArray.count {
                let url = appearArray[index]
                self.dataArr.add(url)
            }
        }
      
        if self.dataArr.count > 1 {
            self.pageControl.numberOfPages = self.dataArr.count
        }else{
            self.pageControl.numberOfPages = 0
        }
        self.collectionView.reloadData()
        
        self.titleLab.text = data.name ?? ""
        
        let tempMileageUnit = XTManageCenter.mileageUnit() //公里
//        let dateStr = XTManageCenter.getDateStringFormat(fromDateFormat: "yyyy-MM-dd HH:mm:ss", toDateFormat: "yyyy", dateString: data.exfactoryDate ?? "") + MMLocalizedString("particular_year", comment: "年")
        let dateStr = (data.exfactoryDate ?? "") + MMLocalizedString("particular_year", comment: "年")
        
        let mileage = XTManageCenter.showPriceInComma(source: (data.mileage ?? 0).cleanZero)
        let engine = XTManageCenter.showPriceInComma(source: data.engine ?? "")
        self.subTitleLab.text = String(format: "%@ | %@%@ | %@cc",
                                       dateStr,
                                       mileage,
                                       tempMileageUnit,
                                       engine)
        
        let price = XTManageCenter.showPriceInComma(source: (data.price ?? 0).cleanZero)
        
        self.priceLab.text = String(format: "%@%@",
                                    XTManageCenter.currentSign(),price)
        self.updateConstraints()
        
    }
}

extension ArticelTitleTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: self.bkgView.frame.size.width, height: self.collectionView.frame.size.height)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return max(self.dataArr.count, 1)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CarBannerCollectionCell", for: indexPath) as! CarBannerCollectionCell
        if self.dataArr.count > indexPath.row {
            cell.imgView.frame.size.height = collectionView.frame.size.height
            cell.imgView.sd_setImage(with: URL.init(string: self.dataArr[indexPath.row] as! String), placeholderImage: UIImage(named: "icon_default_place_h"))
        }else{
            cell.imgView.image = UIImage.init(named: "icon_default_place_h")
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.delegate != nil && self.indexPath != nil {
            self.delegate.didSelectFavoryTableCell(atIndex: self.indexPath)
        }
    }
    
}


extension ArticelTitleTableViewCell: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x/self.bkgView.frame.size.width)
        self.pageControl.currentPage = page
    }
}

